#include "TypeEntryItem.h"
#include "xMappingNode.h"
#include "NodeOutPort.h"
#include "TypeManager.h"
#include "TypeUnfoldButton.h"
#include "TypeEntryFrameItem.h"
#include "TypeVariablePanel.h"

#include <QPainter>
#include <QPen>
#include <QBrush>


using namespace std;

TypeEntryItem::TypeEntryItem(string entryName, string entryType, xMappingNode* entryNode, WOP_Entry* wopEntry, AbstractManager* manager,TypeVariablePanel* panel,TypeEntryFrameItem* entryFrame)
	:PanelItem( entryName, manager , panel)
{
	this->_type = entryType;
	this->_mpnNode  = entryNode;
	this->_wopEntry = wopEntry;

	this->_nodeType = AbstractShapeItem::ENTRY_NODE;
	this->_mpnNode->setForeachElements((_manager->isInForEachRect(this)));
	if (entryFrame!=NULL){
		this->setParent(entryFrame);
	} 
	this->setupPort();
}


TypeEntryItem::~TypeEntryItem(void)
{
}

void TypeEntryItem::setupPort()
{
	for(int i = 0; i< _mpnNode->getOutportSize(); ++i){
		xOutMappingPort* omp = _mpnNode->getOutPort(i);
		_outportList.push_back(new NodeOutPort(omp,this));
	}

	_outportList.at(0)->setX(this->_width - NodePort::RADIUS);
	_outportList.at(0)->setY(HEIGHT / 2 - NodePort::RADIUS + 1);
}

WOP_Entry* TypeEntryItem::getWOPEntry()
{
	return this->_wopEntry;
}

void TypeEntryItem::remove()
{
	assert(false);
}

void TypeEntryItem::removeAllLinks()
{
	std::vector<NodeOutPort*> outPorts = this->getOutportList();
	std::vector<NodeOutPort*>::iterator itr;
	for ( itr = outPorts.begin(); itr != outPorts.end(); ++itr )
	{
		(*itr)->removeAllLinks();
	}
}

void TypeEntryItem::unfold()
{
	if ( this->_type == "object" ){
		TypeManager* manager = dynamic_cast<TypeManager*>(_manager);
		auto children = manager->createUnfoldEntries(this->_wopEntry);

		
		int index = _panel->indexOfItem(this) + 1;
		for ( auto itr = children.begin(); itr != children.end(); ++itr )
		{
			(*itr)->setParent(this);
			this->getMappingNode()->addUnfoldChild((*itr)->getMappingNode());
			_panel->insertItem(*itr, index);
			index++;
		}
	}
	_panel->updateItemsPosition();
}
